<template>
  <div class="adoption-record-container">
    <!-- 搜索和操作栏 -->
    <div class="search-container" style="display: flex; align-items: center; justify-content: space-between;">
      <div class="title">
        <h2>领养记录管理</h2>
      </div>

      <div style="display: flex; align-items: center; gap: 10px;">
        <el-input v-model="searchQuery.applicantName" placeholder="申请人姓名" clearable style="width: 150px" />
        <el-input v-model="searchQuery.petName" placeholder="宠物名称" clearable style="width: 150px" />
        <el-select v-model="searchQuery.status" placeholder="申请状态" clearable style="width: 150px">
          <el-option label="待审核" value="pending" />
          <el-option label="已通过" value="approved" />
          <el-option label="已拒绝" value="rejected" />
          <el-option label="已完成" value="completed" />
        </el-select>
        <el-button type="primary" @click="handleSearch" class="search-btn">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button type="danger" @click="handleClear" class="clear-btn">
          <el-icon><Delete /></el-icon>清除
        </el-button>
      </div>
    </div>

    <!-- 领养记录列表 -->
    <el-table v-loading="loading" :data="recordList" class="custom-table" border stripe>
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="申请人" min-width="120" align="center">
        <template #default="scope">
          <div class="user-info">
            <el-avatar :size="30" :src="`/api/Userfile/${scope.row.user_avatar}`">
              <el-icon><User /></el-icon>
            </el-avatar>
            <span>{{ scope.row.user_name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="宠物信息" min-width="150" align="center">
        <template #default="scope">
          <div class="pet-info">
            <el-image 
              :src="`/api/Petfile/${scope.row.pet_image}`"
              class="pet-image" 
              fit="cover"
              :preview-src-list="[`/api/Petfile/${scope.row.pet_image}`]"
              :hide-on-click-modal="false"
              preview-teleported
            >
              <template #error>
                <el-icon><Picture /></el-icon>
              </template>
            </el-image>
            <span>{{ scope.row.pet_name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="联系电话" prop="user_phone" width="130" align="center" />
      <el-table-column label="申请时间" width="180" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.created_at) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center" fixed="right">
        <template #default="scope">
          <div style="display: flex; justify-content: center; gap: 10px;">
            <el-button type="info" size="small" @click="handleView(scope.row)" class="view-btn">
              <el-icon><View /></el-icon>详情
            </el-button>
            <el-button 
              v-if="scope.row.status === 'pending'" 
              type="success" 
              size="small" 
              @click="handleApprove(scope.row)" 
              class="approve-btn"
            >
              <el-icon><Check /></el-icon>通过
            </el-button>
            <el-button 
              v-if="scope.row.status === 'pending'" 
              type="danger" 
              size="small" 
              @click="handleReject(scope.row)" 
              class="reject-btn"
            >
              <el-icon><Close /></el-icon>拒绝
            </el-button>
            <el-button 
              v-if="scope.row.status === 'approved'" 
              type="primary" 
              size="small" 
              @click="handleComplete(scope.row)" 
              class="complete-btn"
            >
              <el-icon><Check /></el-icon>完成
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      title="领养申请详情"
      v-model="detailDialogVisible"
      width="700px"
      :close-on-click-modal="false"
    >
      <div class="detail-container" v-if="detailData.id">
        <div class="detail-header">
          <div class="status-tag">
            <el-tag :type="getStatusType(detailData.status)" size="large">
              {{ getStatusText(detailData.status) }}
            </el-tag>
          </div>
          <div class="application-id">申请编号: #{{ detailData.id }}</div>
        </div>

        <el-divider content-position="left">申请人信息</el-divider>
        <div class="detail-section">
          <div class="detail-row">
            <div class="detail-item">
              <span class="item-label">申请人:</span>
              <span class="item-value">{{ detailData.user_name }}</span>
            </div>
            <div class="detail-item">
              <span class="item-label">联系电话:</span>
              <span class="item-value">{{ detailData.user_phone }}</span>
            </div>
          </div>
          <div class="detail-row">
            <div class="detail-item">
              <span class="item-label">居住地址:</span>
              <span class="item-value">{{ detailData.address || '未提供' }}</span>
            </div>
            <div class="detail-item">
              <span class="item-label">申请时间:</span>
              <span class="item-value">{{ formatDate(detailData.created_at) }}</span>
            </div>
          </div>
        </div>

        <el-divider content-position="left">宠物信息</el-divider>
        <div class="detail-section pet-section">
          <div class="pet-image-container">
            <el-image 
              :src="`/api/Petfile/${detailData.pet_image}`"
              fit="cover"
              :preview-src-list="[`/api/Petfile/${detailData.pet_image}`]"
              class="detail-pet-image"
            />
          </div>
          <div class="pet-details">
            <h3 class="pet-name">{{ detailData.pet_name }}</h3>
            <div class="pet-info-grid">
              <div class="pet-info-item">
                <span class="item-label">类型:</span>
                <span class="item-value">{{ detailData.pet_type }}</span>
              </div>
              <div class="pet-info-item">
                <span class="item-label">年龄:</span>
                <span class="item-value">{{ detailData.pet_age }}岁</span>
              </div>
              <div class="pet-info-item">
                <span class="item-label">性别:</span>
                <span class="item-value">{{ detailData.pet_gender === 'male' ? '公' : '母' }}</span>
              </div>
            </div>
          </div>
        </div>

        <el-divider content-position="left">申请理由</el-divider>
        <div class="detail-section">
          <div class="reason-content">
            {{ detailData.reason || '申请人未提供申请理由' }}
          </div>
        </div>

        <el-divider content-position="left">审核信息</el-divider>
        <div class="detail-section">
          <div class="review-info" v-if="detailData.status !== 'pending'">
            <div class="detail-row">
              <div class="detail-item">
                <span class="item-label">审核结果:</span>
                <span class="item-value">
                  <el-tag :type="getStatusType(detailData.status)">
                    {{ getStatusText(detailData.status) }}
                  </el-tag>
                </span>
              </div>
              <div class="detail-item">
                <span class="item-label">审核时间:</span>
                <span class="item-value">{{ formatDate(detailData.updated_at) }}</span>
              </div>
            </div>
            <div class="detail-row" v-if="detailData.review_comment">
              <div class="detail-item full-width">
                <span class="item-label">审核备注:</span>
                <span class="item-value">{{ detailData.review_comment }}</span>
              </div>
            </div>
          </div>
          <div class="no-review" v-else>
            <el-empty description="尚未审核" />
          </div>
        </div>

        <div class="dialog-footer" v-if="detailData.status === 'pending'">
          <el-button @click="detailDialogVisible = false" class="cancel-btn">关闭</el-button>
          <el-button type="danger" @click="handleRejectInDialog" class="reject-btn">
            <el-icon><Close /></el-icon>拒绝申请
          </el-button>
          <el-button type="success" @click="handleApproveInDialog" class="approve-btn">
            <el-icon><Check /></el-icon>通过申请
          </el-button>
        </div>
        <div class="dialog-footer" v-else-if="detailData.status === 'approved'">
          <el-button @click="detailDialogVisible = false" class="cancel-btn">关闭</el-button>
          <el-button type="primary" @click="handleCompleteInDialog" class="complete-btn">
            <el-icon><Check /></el-icon>完成领养
          </el-button>
        </div>
        <div class="dialog-footer" v-else>
          <el-button @click="detailDialogVisible = false" class="cancel-btn">关闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      :title="reviewType === 'approve' ? '通过申请' : reviewType === 'reject' ? '拒绝申请' : '完成领养'"
      v-model="reviewDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="reviewFormRef" :model="reviewForm" label-width="80px">
        <el-form-item label="备注信息" prop="comment">
          <el-input 
            v-model="reviewForm.comment" 
            type="textarea" 
            :rows="4" 
            :placeholder="
              reviewType === 'approve' ? '请输入通过申请的备注信息' : 
              reviewType === 'reject' ? '请输入拒绝申请的原因' : 
              '请输入完成领养的备注信息'
            "
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button 
            :type="
              reviewType === 'approve' ? 'success' : 
              reviewType === 'reject' ? 'danger' : 
              'primary'
            " 
            @click="submitReview" 
            class="submit-btn"
          >确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Delete, 
  View, 
  Check, 
  Close, 
  User,
  Picture
} from '@element-plus/icons-vue'
import request from '@/utils/request'

// 列表数据
const loading = ref(false)
const recordList = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 搜索条件
const searchQuery = reactive({
  applicantName: '',
  petName: '',
  status: ''
})

// 详情对话框
const detailDialogVisible = ref(false)
const detailData = ref({})

// 审核对话框
const reviewDialogVisible = ref(false)
const reviewType = ref('') // approve, reject, complete
const reviewForm = reactive({
  id: null,
  comment: '',
  status: '',
  pet_id: null
})
const reviewFormRef = ref(null)

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'pending':
      return 'warning'
    case 'approved':
      return 'success'
    case 'rejected':
      return 'danger'
    case 'completed':
      return 'primary'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending':
      return '待审核'
    case 'approved':
      return '已通过'
    case 'rejected':
      return '已拒绝'
    case 'completed':
      return '已完成'
    default:
      return '未知'
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取领养记录列表
const getRecordList = async () => {
  loading.value = true
  try {
    const res = await request.get('/applications/applicationSearch', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        applicantName: searchQuery.applicantName,
        petName: searchQuery.petName,
        status: searchQuery.status
      }
    })
    if (res.code === 200 && res.data) {
      recordList.value = res.data.list
      total.value = res.data.total
      
      if (recordList.value.length === 0 && currentPage.value > 1) {
        currentPage.value--
        await getRecordList()
        return
      }
    } else {
      recordList.value = []
      total.value = 0
      ElMessage.warning('未找到相关数据')
    }
  } catch (error) {
    console.error('获取领养记录列表失败:', error)
    ElMessage.error('获取列表失败')
    recordList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getRecordList()
}

// 清除搜索条件
const handleClear = () => {
  Object.keys(searchQuery).forEach(key => {
    searchQuery[key] = ''
  })
  currentPage.value = 1
  getRecordList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getRecordList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getRecordList()
}

// 查看详情
const handleView = (row) => {
  detailData.value = { ...row }
  detailDialogVisible.value = true
}

// 通过申请
const handleApprove = (row) => {
  reviewType.value = 'approve'
  reviewForm.id = row.id
  reviewForm.comment = ''
  reviewForm.status = 'approved'
  reviewForm.pet_id = row.pet_id
  reviewDialogVisible.value = true
}

// 拒绝申请
const handleReject = (row) => {
  reviewType.value = 'reject'
  reviewForm.id = row.id
  reviewForm.comment = ''
  reviewForm.status = 'rejected'
  reviewForm.pet_id = row.pet_id
  reviewDialogVisible.value = true
}

// 完成领养
const handleComplete = (row) => {
  reviewType.value = 'complete'
  reviewForm.id = row.id
  reviewForm.comment = ''
  reviewForm.status = 'completed'
  reviewForm.pet_id = row.pet_id
  reviewDialogVisible.value = true
}

// 在详情对话框中通过申请
const handleApproveInDialog = () => {
  handleApprove(detailData.value)
}

// 在详情对话框中拒绝申请
const handleRejectInDialog = () => {
  handleReject(detailData.value)
}

// 在详情对话框中完成领养
const handleCompleteInDialog = () => {
  handleComplete(detailData.value)
}

// 提交审核
const submitReview = async () => {
  try {
    const res = await request.post('/applications/applicationAdd', {
      id: reviewForm.id,
      status: reviewForm.status,
      review_comment: reviewForm.comment,
      pet_id: reviewForm.pet_id
    })
    
    if (res.code === 200) {
      ElMessage.success(
        reviewType.value === 'approve' ? '已通过申请' : 
        reviewType.value === 'reject' ? '已拒绝申请' : 
        '已完成领养'
      )
      reviewDialogVisible.value = false
      detailDialogVisible.value = false
      getRecordList()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

onMounted(() => {
  getRecordList()
})
</script>

<style scoped lang="scss">
.adoption-record-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  h2 {
    margin: 0;
    font-size: 20px;
    color: #2f3447;
  }
}

.search-container {
  margin-bottom: 20px;
}

.search-btn {
  background-color: #f9dee1;
  border-color: #f9dee1;
  color: #2f3447;
  &:focus {
    outline: none !important;
  }
}

.search-btn:hover {
  background-color: #f5c5cb;
  border-color: #f5c5cb;
}

.clear-btn {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  &:focus {
    outline: none !important;
  }
}

.clear-btn:hover {
  background-color: #ff7875;
  border-color: #ff7875;
}

.custom-table {
  margin: 20px 0;
  border-radius: 8px;
  overflow: hidden;
}

.user-info, .pet-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.pet-image {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}

.view-btn {
  background-color: #909399;
  border-color: #909399;
  color: #fff;
  &:focus {
    outline: none !important;
  }
}

.view-btn:hover {
  background-color: #a6a9ad;
  border-color: #a6a9ad;
}

.approve-btn {
  background-color: #67c23a;
  border-color: #67c23a;
  &:focus {
    outline: none !important;
  }
}

.approve-btn:hover {
  background-color: #85ce61;
  border-color: #85ce61;
}

.reject-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
  &:focus {
    outline: none !important;
  }
}

.reject-btn:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.complete-btn {
  background-color: #409eff;
  border-color: #409eff;
  &:focus {
    outline: none !important;
  }
}

.complete-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 详情对话框样式 */
.detail-container {
  padding: 0 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.application-id {
  font-size: 14px;
  color: #909399;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-row {
  display: flex;
  margin-bottom: 15px;
}

.detail-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.full-width {
  flex: 2;
}

.item-label {
  font-size: 14px;
  color: #909399;
}

.item-value {
  font-size: 14px;
  color: #303133;
}

.pet-section {
  display: flex;
  gap: 20px;
}

.pet-image-container {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
}

.detail-pet-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.pet-details {
  flex: 1;
}

.pet-name {
  margin: 0 0 15px 0;
  font-size: 18px;
  color: #303133;
}

.pet-info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.pet-info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.reason-content {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  min-height: 80px;
}

.no-review {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
}

.cancel-btn {
  background-color: #f9dee1;
  border-color: #f9dee1;
  color: #2f3447;
  &:focus {
    outline: none !important;
  }
}

.cancel-btn:hover {
  background-color: #f5c5cb;
  border-color: #f5c5cb;
}

.submit-btn {
  &:focus {
    outline: none !important;
  }
}
</style>